package com.yuyou.tas.feedback.service.impl;

import com.yuyou.tas.feedback.IWeixinFIleService;
import com.yuyou.tas.feedback.service.IQiniuService;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.LogUtil;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinFIleServiceImpl implements IWeixinFIleService {

    private static final Logger logger  = LoggerFactory.getLogger(WeixinFIleServiceImpl.class);

    
    @Autowired
    private IQiniuService qiniuService;

    @Override
    public String upload2Qiniu(String serverId, String type){
        String url  = "http://wx.yuyou100.com/teacher/wechat/downloadMedia?mediaId=" ;
        Request request = new Request.Builder().url(url + serverId ).build() ;
        Response response =  null ;
        try{
        	
            OkHttpClient okHttpClient = new OkHttpClient().
            		newBuilder().readTimeout(120000, TimeUnit.MILLISECONDS)
            		.writeTimeout(120000, TimeUnit.MILLISECONDS)
            		.connectTimeout(120000, TimeUnit.MILLISECONDS).build();
            
            response = okHttpClient.newCall(request).execute();
            InputStream inputStream = response.body().byteStream();
            return qiniuService.upload(inputStream , type );
        }catch (Exception e){
        	LogUtil.error(logger, "upload2Qiniu,微信图片上传七牛云异常:",e);
            throw new BusinessException("upload2Qiniu,微信图片上传七牛云异常:"+e.getMessage());
        }finally {
            if(response != null ){
                response.close();
            }
        }
    }
}
